package com.sc.VenusQueryBeta.ui.fragments.account.daikuan;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.account.daikuan.DaiKuanAdapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.daikuan.DaiKuanContract;
import com.sc.VenusQueryBeta.model.bean.account.AccountList;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.presenter.account.daikuan.DaiKuanPresenter;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

public class DaiKuanFragment extends BaseMVPCompatFragment<DaiKuanContract.DaiKuanPresenter> implements DaiKuanContract.IDaiKuanView {

    private static DaiKuanFragment fragment;
    @BindView(R.id.ibtn_daikuan_back)
    ImageButton ibtnDaikuanBack;
    @BindView(R.id.vip_uservip_user_infornation)
    RecyclerView rvdaikuan;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.total_money)
    TextView totalMoney;
    private DaiKuanAdapter daiKuanAdapter;
    private CustomPopWindow mClubPopWindow;
    private PopAdapter popAdapter;
    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private int roomId;
    private String roomyear;
    private String roommonth;
    private CurrencyListBean mallRoomListBean;//所有廳
    private RecyclerView clubrecyclerView;
    private String currency;


    public static DaiKuanFragment newInstance(QueryRegisBean queryRegisBean, int clientindex, String currency_type) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        args.putString(Constants.CURRENCY_TYPE, currency_type);
        fragment = new DaiKuanFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
            //查询所有厅
            showProgressDialog("正在加载...");
            mPresenter.queryAllCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        } else {
            ToastUtils.showToast("数据异常");
        }
    }

//    /**
//     * 初始化头部
//     */
//    private void initHeadView() {
//        if (headView == null) {
//            headView = ResourcesUtils.inflate(R.layout.rv_top);
//        }
//        if (errorView == null) {
//            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
//        }
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, roomyear + "", roommonth + "", "3", "0", currency);
//            }
//        });
//        btn_choose_club = headView.findViewById(R.id.chooise_company);
//        total_money = headView.findViewById(R.id.total_money);
//        btn_choose_time = headView.findViewById(R.id.chooise_time);//时间button
//        btn_choose_time.setVisibility(View.GONE);
//        btn_choose_time.setText(roomyear + "/" + roommonth);//设置日期
//
//
//    }

    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //处理popWindow 显示内容

        //创建并显示popWindow
        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .setView(contentView).setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        mActivity.getWindow().setAttributes(lp);
                    }
                })
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);

    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mContext);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部

        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                      mAdapterWithHF.notifyDataSetChanged();//适配器更新数据
                        if (mPresenter != null && ptrClass != null) {
                            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                                daiKuanAdapter.removeAllHeaderView();//必須先remove headview
                                //查询子户口
                                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                        clientindex,  "", "", "3", "0", chooiseCompany.getText().toString());
                            } else {
                                ToastUtils.showToast("数据异常");
                            }
                        } else {
                            hideProgressDialog();
                        }
                        if (ptrClass != null) {
                            ptrClass.refreshComplete();
                        } else {
                            hideProgressDialog();
                        }
                    }
                }, 1000);
            }
        });
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_dai_kuan;
    }

    /**
     * 贷款
     *
     * @param savedInstanceState savedInstanceState
     */
    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        chooiseCompany.setText(currency);
        //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
        daiKuanAdapter = new DaiKuanAdapter(R.layout.item_zhuanma);
        rvdaikuan.setAdapter(daiKuanAdapter);
        rvdaikuan.setLayoutManager(new LinearLayoutManager(mActivity));
        Calendar c = Calendar.getInstance();//
        roomyear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
        roommonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
//        initHeadView();//初始化头部布局
        initClub();//初始化集團佈局
    }

    @Override
    public void initData() {
        super.initData();
        if (fragment.getArguments() != null) {
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
            currency = fragment.getArguments().getString(Constants.CURRENCY_TYPE);
        }
    }


    /**
     * 填充户口适配器\
     *
     * @param accountListBean
     */
    private void initRvList(final AccountList accountListBean) {
        daiKuanAdapter = new DaiKuanAdapter(R.layout.item_zhuanma, accountListBean.getClients());
        daiKuanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {//監聽item 劍點擊
                LogUtils.e("room  " + roomyear + roommonth + roommonth);
//
                start(DaiKuan01Fragment.newInstance(queryRegisBean, clientindex, roomId, chooiseCompany.getText().toString()));
            }
        });
        rvdaikuan.setAdapter(daiKuanAdapter);
//        daiKuanAdapter.addHeaderView(headView);//动态添加头部布局
        reFreshListener();//rv下拉刷新
        ptrClass.refreshComplete();//

    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return DaiKuanPresenter.newInstance();
    }


    @OnClick({R.id.ibtn_daikuan_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_daikuan_back:
                pop();
                break;
        }
    }

    @Override
    public void showNetworkError(Throwable throwable) {
//        daiKuanAdapter.setEmptyView(errorView);
        LogUtils.e("不调用回调");
        hideProgressDialog();
        ptrClass.refreshComplete();
    }

    @Override
    public void showqueryAllCurrencyList(final CurrencyListBean currencyListBean) {
        if (currencyListBean != null && currencyListBean.getCurrencys().size() > 0) {
//            roomId = Integer.parseInt(allRoomListBean.getRoomList().get(0).getRoomid());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
//                   roomId = Integer.parseInt(currencyListBean.getRoomList().get(position).getRoomid());
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱

                    //查詢子戶口
                    showProgressDialog("正在加载");
//                        daiKuanAdapter.removeAllHeaderView();

                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                            clientindex, "", "", "3", "0", chooiseCompany.getText().toString());
                    mClubPopWindow.dissmiss();
                }
            });
            //填充廳數據

            mallRoomListBean = currencyListBean;
//            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                //查询子户口
                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                        clientindex,  "",  "", "3", "0",chooiseCompany.getText().toString() );
            }
        }
    }

//    @Override
//    public void showqueryAllRoomList(final AllRoomListBean allRoomListBean) {
//        if (allRoomListBean != null && allRoomListBean.getRoomList().size() > 0) {
//            roomId = Integer.parseInt(allRoomListBean.getRoomList().get(0).getRoomid());
//            //填充廳數據
//            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
//            popAdapter = new PopAdapter(R.layout.pop_list_item, allRoomListBean.getRoomList());
//            clubrecyclerView.setAdapter(popAdapter);
//            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//            //集團點擊監聽
//            popAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                    roomId = Integer.parseInt(allRoomListBean.getRoomList().get(position).getRoomid());
//                    btn_choose_club.setText(allRoomListBean.getRoomList().get(position).getRoomname());//動態改變集團名稱
//
//                    //查詢子戶口
//                    showProgressDialog("正在加载");
////                        daiKuanAdapter.removeAllHeaderView();
//
//                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                            clientindex, roomId, roomyear + "", roommonth + "", "3", "0");
//                    mClubPopWindow.dissmiss();
//                }
//            });
//            //填充廳數據
//
//            mallRoomListBean = allRoomListBean;
////            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
////            //查询子户口
//            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                //查询子户口
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, roomId, roomyear + "", roommonth + "", "3", "0");
//            }
//        }
//    }

    @Override
    public void showZiHuKouList(AccountList accountListBean) {
        if (accountListBean != null && accountListBean.getClients() != null && accountListBean.getClients().size() > 0) {
            daiKuanAdapter.removeAllHeaderView();
            initRvList(accountListBean);
        }
        hideProgressDialog();
//        initRvList(accountListBean);
        chooiseCompany.setOnClickListener(new View.OnClickListener() {//选择集团監聽
            @Override
            public void onClick(View view) {
                mClubPopWindow.showAsDropDown(chooiseCompany, -20, 20);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 0.5f;
                mActivity.getWindow().setAttributes(lp);
            }
        });

        totalMoney.setText(accountListBean.getCommonValueSum() + "萬");//设置总金额
    }
//
//    @OnClick(R.id.chooise_company)
//    public void onViewClicked() {
//        chooiseCurrency();
//    }
//    private void chooiseCurrency() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0, CENTER);
//        } else {
//            mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0);
//        }
//    }


}
